package pers.corvey.studyjava.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;

import pers.corvey.studyjava.MyConstant;

public class CookieUtils {
    
    public static String getCookieValueByName(HttpServletRequest request, String name) {
        Cookie cookie = getCookieByName(request, name);
        return cookie != null ? cookie.getValue() : null;
    }
    
    public static void createCookie(HttpServletResponse response, String name, String value) {
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(MyConstant.COOKIE_MAX_AGE);
        response.addCookie(cookie);
    }

    public static void removeCookieByName(HttpServletResponse response, String name) {
        Cookie cookie = new Cookie(name, "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }
    
    private static Cookie getCookieByName(HttpServletRequest request, String name) {
        if (name == null || name.equals("")) {
            return null;
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (name.equals(cookie.getName())) {
                    return cookie;
                }
            }
        }
        return null;
    }
    
}
